<template>
  <div class="bg-white task-handle-container">
    <div class="handle_type">{{ handleType }}</div>
    <div class="form-conatiner">
      <ElForm :model="form" label-width="auto" ref="taskFormRef">
        <ElFormItem label="标题">
          <ElInput v-model="form.title" placeholder="请输入帖子标题，最多80字" maxlength="80" />
        </ElFormItem>
        <ElFormItem label="描述">
          <ElInput
            v-model="form.description"
            type="textarea"
            placeholder="请简单介绍帖子的内容，最多200字"
            maxlength="200"
          />
        </ElFormItem>
        <ElFormItem label="内容">
          <Markdown v-model="form.content" />
        </ElFormItem>
        <ElFormItem label="截止时间">
          <ElDatePicker
            v-model="form.endTime"
            type="datetime"
            :disabled-date="disabledDate"
            style="width: 50%"
            size="large"
          />
        </ElFormItem>
        <ElFormItem label="任务类型">
          <ElRadioGroup v-model="form.type">
            <ElRadio v-for="item in taskType" :key="item.value" :value="item.value">{{
              item.label
            }}</ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="赏金金额">
          <ElInputNumber
            v-model.number="form.bounty"
            :precision="2"
            size="large"
            style="width: 50%"
            controls-position="right"
            :min="0"
          />
        </ElFormItem>
        <ElFormItem label="赏金数量">
          <ElInputNumber
            v-model.number="form.bountyNum"
            size="large"
            style="width: 50%"
            controls-position="right"
            :min="0"
          />
        </ElFormItem>
        <ElFormItem label="图片" prop="images" required>
          <ElUpload
            action="#"
            list-type="picture-card"
            :http-request="handleUpload"
            :file-list="uploadedFiles"
            @change="handleChange"
          >
            <ElIcon><Plus /></ElIcon>
            <template #file>
              <div v-for="(file, index) in uploadedFiles" :key="index">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <ElIcon><zoom-in /></ElIcon>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete">
                    <ElIcon
                      ><a :href="file.url"><Download /></a
                    ></ElIcon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <ElIcon><Delete /></ElIcon>
                  </span>
                </span>
              </div>
            </template>
          </ElUpload>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="handleSubmit" class="submit_btn">提交</ElButton>
        </ElFormItem>
      </ElForm>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import Markdown from '@/components/Markdown.vue'
import { useRoute, useRouter } from 'vue-router'
import { ElInputNumber } from 'element-plus'

const taskFormRef = ref()

const route = useRoute()
const router = useRouter()
const handleType = computed(() => {
  return route.query.id ? '修改任务' : '新增任务'
})

const taskId = computed(() => route.query?.id as string)

interface Form{
  title: string,
  description: string,
  content: string,
  endTime: number,
  type: number,
  bounty: number,
  bountyNum: number,
  x: number,
  y: number,
  images: string[],
}

const form = reactive<Form>({
  title: '',
  description: '',
  content: '',
  endTime: 0,
  type: 0,
  bounty: 0,
  bountyNum: 0,
  x: 0,
  y: 0,
  images: [],
})

const getTaskInfo = async (id:number|string) => {
  const result = await service.task.findById(id)
  Object.assign(form, result.data)
  uploadedFiles.value = form.images.map((ele) => ({
    url: ele,
  }))
}
onMounted(() => {
  if (taskId.value != undefined) {
    getTaskInfo(taskId.value)
  }
})

const taskType = [
  {
    label: '普通帖',
    value: 0,
  },
  {
    label: '任务帖',
    value: 1,
  },
  {
    label: '求助帖',
    value: 2,
  },
]

const disabledDate = (date:Date) => {
  const now = Date.now()
  return date.getTime() <= now - 8.64e7
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const uploadedFiles = ref<any>([])

const handleUpload = async (options: any) => {
  const data = {
    file: options.file,
    filename: options.file.name,
    onProgress: options.onProgress,
  }
  const result = await service.common.upload(data) 
  form.images.push(result)
  uploadedFiles.value.push({ url: result })
}
const handleRemove = (file: any) => {
  uploadedFiles.value = uploadedFiles.value.filter((ele:{url:string}) => ele.url != file.url)
  form.images = form.images.filter((ele) => ele != file.url)
  taskFormRef.value.validateField('images')
}

const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleChange = () => {
  taskFormRef.value.validateField('images')
}

const handleSubmit = () => {
  taskFormRef.value.validate().then(async (success:boolean) => {
    if (success) {
      form.endTime = form.endTime.valueOf()
      if (taskId.value != undefined) {
        await service.task.update(form)
      } else {
        await service.task.add(form)
      }
      router.push('/main/home')
    }
  })
}
</script>

<style lang="scss" scoped>
.task-handle-container {
  padding: 20px 0;

  .handle_type {
    padding: 0 20px 10px;
    margin-bottom: 10px;
    border-bottom: 2px solid rgba(0, 0, 0, 10%);
  }

  .form-conatiner {
    padding: 0 20px;

    .submit_btn {
      width: 300px;
      margin: 0 auto;
    }
  }
}
</style>
